package com.example.spring_config.aop;

import com.example.spring_config.anno.PermissionVerAnno;
import com.example.spring_config.bean.ResultInfo;
import com.example.spring_config.mapper.Permission;
import com.example.spring_config.util.CheckUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private HttpSession session;

    /**
     * 判断用户是否拥有此权限
     * @param point
     * @param anno
     * @return
     */
    @Around("@annotation(anno)")
    public Object test02(ProceedingJoinPoint point, PermissionVerAnno anno){
        Object result = null;
        try {
            // 获取用户的权限
            Set<String> userPermission = (Set<String>) session.getAttribute("userPermission");
            String value = anno.value();
            boolean flag = true;
            for (String s : userPermission) {
                if(!s.contains(value)){
                    flag = false;
                }
            }

            // 判断权限是否被禁用
            Map<String,Permission> allPermissionMap = (Map<String,Permission>) session.getAttribute("allPermissionMap");
            flag = CheckUtil.checkPermission(allPermissionMap, value);
            if(flag){
                result = point.proceed(point.getArgs());
            }else {
                result = ResultInfo.no("您未拥有此权限或者权限已经被禁用");
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("异常通知");
        }finally {
            System.out.println("最终通知");
        }
        return result;
    }

}
